<template>
  <div class="runtime-error-debug">
    <h1>运行时错误调试</h1>
    
    <div class="debug-sections">
      <!-- 错误信息 -->
      <div class="debug-section">
        <h2>🚨 当前错误</h2>
        <div class="error-display">
          <div class="error-item">
            <h3>Message Port 错误</h3>
            <div class="error-code">
              Unchecked runtime.lastError: The message port closed before a response was received.
            </div>
            <div class="error-details">
              <p><strong>错误类型：</strong>浏览器扩展通信错误</p>
              <p><strong>影响程度：</strong>不影响应用功能，但会在控制台显示警告</p>
              <p><strong>常见原因：</strong></p>
              <ul>
                <li>浏览器扩展与页面通信中断</li>
                <li>Chrome 开发者工具扩展冲突</li>
                <li>页面刷新时扩展连接未正确关闭</li>
              </ul>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 诊断工具 -->
      <div class="debug-section">
        <h2>🔍 诊断工具</h2>
        <div class="diagnostic-tools">
          <div class="tool-group">
            <h3>浏览器信息</h3>
            <div class="info-grid">
              <div class="info-item">
                <label>用户代理：</label>
                <span class="info-value">{{ userAgent }}</span>
              </div>
              <div class="info-item">
                <label>浏览器：</label>
                <span class="info-value">{{ browserInfo }}</span>
              </div>
              <div class="info-item">
                <label>当前URL：</label>
                <span class="info-value">{{ currentUrl }}</span>
              </div>
            </div>
          </div>
          
          <div class="tool-group">
            <h3>扩展检测</h3>
            <div class="extension-check">
              <button @click="checkExtensions" class="check-btn">检测浏览器扩展</button>
              <div v-if="extensionCheckResult" class="check-result">
                <p>{{ extensionCheckResult }}</p>
              </div>
            </div>
          </div>
          
          <div class="tool-group">
            <h3>控制台清理</h3>
            <div class="console-tools">
              <button @click="clearConsole" class="action-btn">清理控制台</button>
              <button @click="suppressWarnings" class="action-btn">抑制警告</button>
              <button @click="restoreWarnings" class="action-btn">恢复警告</button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 解决方案 -->
      <div class="debug-section">
        <h2>🔧 解决方案</h2>
        <div class="solutions">
          <div class="solution-item">
            <h3>方案 1：禁用问题扩展</h3>
            <div class="solution-steps">
              <ol>
                <li>打开 Chrome 设置 → 扩展程序</li>
                <li>逐个禁用扩展，特别是开发者工具相关扩展</li>
                <li>刷新页面查看错误是否消失</li>
                <li>找到问题扩展后可选择禁用或卸载</li>
              </ol>
            </div>
          </div>
          
          <div class="solution-item">
            <h3>方案 2：使用无痕模式</h3>
            <div class="solution-steps">
              <ol>
                <li>按 <code>Ctrl+Shift+N</code> 打开无痕窗口</li>
                <li>在无痕模式下访问应用</li>
                <li>无痕模式默认禁用大部分扩展</li>
                <li>如果错误消失，说明是扩展问题</li>
              </ol>
            </div>
          </div>
          
          <div class="solution-item">
            <h3>方案 3：代码级别抑制</h3>
            <div class="solution-steps">
              <p>在应用中添加错误抑制代码：</p>
              <div class="code-block">
                <code>
// 抑制 runtime.lastError 警告<br>
window.addEventListener('error', (e) => {<br>
  if (e.message.includes('message port closed')) {<br>
    e.preventDefault()<br>
    return false<br>
  }<br>
})
                </code>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 预防措施 -->
      <div class="debug-section">
        <h2>🛡️ 预防措施</h2>
        <div class="prevention-tips">
          <div class="tip-item">
            <h4>开发环境</h4>
            <ul>
              <li>定期清理浏览器缓存和数据</li>
              <li>使用专门的开发浏览器配置文件</li>
              <li>避免安装过多开发者扩展</li>
              <li>定期更新浏览器和扩展</li>
            </ul>
          </div>
          
          <div class="tip-item">
            <h4>生产环境</h4>
            <ul>
              <li>添加全局错误处理器</li>
              <li>监控和记录客户端错误</li>
              <li>提供用户友好的错误提示</li>
              <li>定期测试不同浏览器环境</li>
            </ul>
          </div>
        </div>
      </div>
      
      <!-- 状态监控 -->
      <div class="debug-section">
        <h2>📊 状态监控</h2>
        <div class="status-monitor">
          <div class="status-item">
            <label>页面加载状态：</label>
            <span class="status-value" :class="pageStatus">{{ pageStatus }}</span>
          </div>
          <div class="status-item">
            <label>错误计数：</label>
            <span class="status-value">{{ errorCount }}</span>
          </div>
          <div class="status-item">
            <label>最后错误时间：</label>
            <span class="status-value">{{ lastErrorTime || '无' }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'

// 响应式数据
const userAgent = ref('')
const browserInfo = ref('')
const currentUrl = ref('')
const extensionCheckResult = ref('')
const pageStatus = ref('loaded')
const errorCount = ref(0)
const lastErrorTime = ref('')

// 初始化
onMounted(() => {
  userAgent.value = navigator.userAgent
  browserInfo.value = getBrowserInfo()
  currentUrl.value = window.location.href
  
  // 监听错误
  setupErrorMonitoring()
})

// 获取浏览器信息
const getBrowserInfo = () => {
  const ua = navigator.userAgent
  if (ua.includes('Chrome')) return 'Chrome'
  if (ua.includes('Firefox')) return 'Firefox'
  if (ua.includes('Safari')) return 'Safari'
  if (ua.includes('Edge')) return 'Edge'
  return '未知浏览器'
}

// 检测扩展
const checkExtensions = () => {
  // 检测常见的扩展特征
  const extensions = []
  
  // 检测 Vue DevTools
  if (window.__VUE_DEVTOOLS_GLOBAL_HOOK__) {
    extensions.push('Vue DevTools')
  }
  
  // 检测 React DevTools
  if (window.__REACT_DEVTOOLS_GLOBAL_HOOK__) {
    extensions.push('React DevTools')
  }
  
  // 检测其他常见扩展标识
  if (window.chrome && window.chrome.runtime) {
    extensions.push('Chrome 扩展环境')
  }
  
  extensionCheckResult.value = extensions.length > 0 
    ? `检测到扩展: ${extensions.join(', ')}` 
    : '未检测到明显的扩展标识'
}

// 清理控制台
const clearConsole = () => {
  console.clear()
  console.log('控制台已清理')
}

// 抑制警告
const suppressWarnings = () => {
  // 保存原始的 console.warn
  if (!window._originalWarn) {
    window._originalWarn = console.warn
  }
  
  console.warn = (...args) => {
    const message = args.join(' ')
    if (!message.includes('message port closed') && !message.includes('runtime.lastError')) {
      window._originalWarn(...args)
    }
  }
  
  console.log('已抑制 runtime.lastError 相关警告')
}

// 恢复警告
const restoreWarnings = () => {
  if (window._originalWarn) {
    console.warn = window._originalWarn
    console.log('已恢复所有警告')
  }
}

// 设置错误监控
const setupErrorMonitoring = () => {
  window.addEventListener('error', (e) => {
    errorCount.value++
    lastErrorTime.value = new Date().toLocaleTimeString()
    
    if (e.message.includes('message port closed')) {
      console.log('检测到 message port 错误，已记录')
      e.preventDefault()
      return false
    }
  })
  
  // 监听未处理的 Promise 拒绝
  window.addEventListener('unhandledrejection', (e) => {
    errorCount.value++
    lastErrorTime.value = new Date().toLocaleTimeString()
    console.log('检测到未处理的 Promise 拒绝:', e.reason)
  })
}
</script>

<style scoped>
.runtime-error-debug {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.debug-sections {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.debug-section {
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background: #f9f9f9;
}

.debug-section h2 {
  margin-bottom: 20px;
  color: #333;
  border-bottom: 2px solid #409EFF;
  padding-bottom: 10px;
}

.error-display {
  background: white;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #eee;
}

.error-item h3 {
  color: #e74c3c;
  margin-bottom: 10px;
}

.error-code {
  background: #f8f8f8;
  padding: 15px;
  border-radius: 4px;
  font-family: monospace;
  color: #e74c3c;
  margin: 10px 0;
  border-left: 4px solid #e74c3c;
}

.error-details ul {
  margin: 10px 0;
  padding-left: 20px;
}

.diagnostic-tools {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.tool-group {
  background: white;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #eee;
}

.tool-group h3 {
  color: #409EFF;
  margin-bottom: 15px;
}

.info-grid {
  display: grid;
  gap: 10px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.info-item label {
  font-weight: 500;
  min-width: 100px;
}

.info-value {
  font-family: monospace;
  background: #f5f5f5;
  padding: 4px 8px;
  border-radius: 4px;
  word-break: break-all;
}

.check-btn, .action-btn {
  background: #409EFF;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 10px;
  margin-bottom: 10px;
}

.check-btn:hover, .action-btn:hover {
  background: #66b1ff;
}

.check-result {
  margin-top: 10px;
  padding: 10px;
  background: #f0f9ff;
  border-radius: 4px;
  border-left: 4px solid #409EFF;
}

.solutions {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.solution-item {
  background: white;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #eee;
}

.solution-item h3 {
  color: #27ae60;
  margin-bottom: 15px;
}

.solution-steps ol {
  margin: 10px 0;
  padding-left: 20px;
}

.solution-steps li {
  margin: 8px 0;
  line-height: 1.6;
}

.code-block {
  background: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
  margin: 10px 0;
  overflow-x: auto;
}

.code-block code {
  font-family: monospace;
  color: #2c3e50;
  line-height: 1.6;
}

.prevention-tips {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.tip-item {
  background: white;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #eee;
}

.tip-item h4 {
  color: #409EFF;
  margin-bottom: 15px;
}

.tip-item ul {
  margin: 0;
  padding-left: 20px;
}

.tip-item li {
  margin: 8px 0;
  line-height: 1.6;
}

.status-monitor {
  background: white;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #eee;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 10px 0;
}

.status-item label {
  font-weight: 500;
  min-width: 120px;
}

.status-value {
  padding: 4px 12px;
  border-radius: 4px;
  font-weight: 500;
}

.status-value.loaded {
  background: #d4edda;
  color: #155724;
}

code {
  background: #f5f5f5;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: monospace;
  color: #e74c3c;
}
</style>
